package com.dmcloud.order.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.dmcloud.common.util.reponse.ResultMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.web.bind.annotation.*;

/**
 * Created by xiaodao
 * date: 2019/11/6
 */
@RestController
@RequestMapping("/orders")
@Slf4j
public class OrderController {
    @Autowired
    private OAuth2RestTemplate restTemplate;

    @PostMapping("/create")
//    @PreAuthorize("#oauth2.hasScope('write')")
    @PreAuthorize("hasRole('ROLE_1')")
    @SentinelResource(value = "createOrder", blockHandler = "doOnBlock")
    public ResultMessage create( @AuthenticationPrincipal String username) throws InterruptedException {

        log.info("order username {}", username);
        Thread.sleep(RandomUtils.nextInt(100,1000));
//        throw new RuntimeException("haha, test");
        return ResultMessage.success(username);
    }

/*    public ResultMessage doOnBlock(String id, @AuthenticationPrincipal String username, BlockedException block) throws InterruptedException{
        //TODO 目前降级不好使
        log.info("block by: " + block.getClass().getSimpleName());
        return ResultMessage.success("请稍后再试");
    }*/

    @GetMapping("/getInfo/{id}")
    @SentinelResource("getInfo")
    public ResultMessage getInfo(@PathVariable String id, @AuthenticationPrincipal String username) {

        log.info("create success id is:  {} username = {}", id, username);
        return ResultMessage.success(id);
    }
    @SentinelResource("create1")
    @PostMapping("/create1")
    public ResultMessage create1(String id, @AuthenticationPrincipal String username){

        log.info("create success id is:  {}  user.username = {}",id,username);
        return ResultMessage.success(id);
    }
 /*
    @PostMapping("/create2")
    public ResultMessage create2(String id, @AuthenticationPrincipal DmUser user){
String user = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                .getHeader("username");
        log.info("create success id is:  {}  user.username = {}",id,user);
        return ResultMessage.success(id);
    }*/
}
